/**
 * Copyright (c) 2018-2028, Chill Zhuang 庄骞 (smallchill@163.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.babble.subitem.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.babble.manage.entity.Img;
import com.babble.manage.feign.IImgClient;
import com.babble.subitem.conversion.SubjectConversion;
import com.babble.subitem.dto.SubjectSaveDTO;
import com.babble.subitem.dto.SubjectUpdDTO;
import com.babble.subitem.entity.Subject;
import com.babble.subitem.mapper.SubjectMapper;
import com.babble.subitem.service.ISubjectService;
import com.babble.subitem.vo.SubjectVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springblade.common.cache.CacheNames;
import org.springblade.common.enums.CodeMsg;
import org.springblade.common.exception.MsgException;
import org.springblade.common.tool.PageUtil;
import org.springblade.core.secure.utils.SecureUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.RedisUtil;
import org.springblade.core.tool.utils.StringUtil;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 专题表 服务实现类
 *
 * @author Blade
 * @since 2021-11-21
 */
@Service
@RequiredArgsConstructor
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements ISubjectService {
	public final SubjectConversion subjectConversion;
	public final RedisUtil redisUtil;
	public final IImgClient imgClient;
	@Override
	public IPage<SubjectVO> selectSubjectPage(IPage<SubjectVO> page, SubjectVO subject) {
		return page.setRecords(baseMapper.selectSubjectPage(page, subject));
	}

	@Override
	public List<Subject> selectSubjects(Map<String, String> map) throws MsgException {
		List<Subject> list = subjjectList();
		String num = map.get("num");
		String size = map.get("size");
		if(num!=null&&size!=null){
			try {
				int sizeOn = Integer.parseInt(size);
				int numOn = Integer.parseInt(num);
				List<Subject> subjects = list.subList(sizeOn * numOn, sizeOn+1);
				return PageUtil.startPage(list,numOn,sizeOn);
			}catch (Exception e){
				throw new MsgException(CodeMsg.SUBJECT_ARRAY_FROMINDEX.getCode(),CodeMsg.SUBJECT_ARRAY_FROMINDEX.getMsg());
			}
		}
 		return list;
	}

	@Override
	public void clickSubject(String id) throws MsgException {
		List<Subject> subjects = getSubjcetIsId(id);
		if(subjects==null || subjects.size()==0){
			throw new MsgException(CodeMsg.SUBJCET_EXISTS_ERROR.getCode(),CodeMsg.SUBJCET_EXISTS_ERROR.getMsg());
		}
		Subject entity = subjects.get(0);
		Long userId = SecureUtil.getUser().getUserId();
		Object json = redisUtil.get(CacheNames.BLOG_SUBJECT_CLICK_TAGS+userId+":"+id);
		if(json==null){
			entity.setClickCount(entity.getClickCount()+1);
			this.updateById(entity);
			redisUtil.set(CacheNames.BLOG_SUBJECT_CLICK_TAGS+userId+":"+id,"0",60, TimeUnit.SECONDS);
			clickToSubject(entity.getId());
			return;
		}
		throw new MsgException(CodeMsg.SUBJECT_CLICK_EXISTS_ERROR.getCode(),CodeMsg.SUBJECT_CLICK_EXISTS_ERROR.getMsg());

	}

	/**
	 * 获取专题集合
	 * @return
	 */
	public List<Subject> subjjectList(){
		Object json = redisUtil.get(CacheNames.BLOG_SUBJECTS);
		if(json==null){
			List<Subject> list = this.list(new QueryWrapper<Subject>().orderByAsc("click_count").orderByAsc("update_time"));
			redisUtil.set(CacheNames.BLOG_SUBJECTS,JSON.toJSON(list));
			return list;
		}
		List<Subject> tags = JSONArray.parseArray(json.toString(), Subject.class);
		return tags;
	}
	@Override
	public List<Subject> getSubjcetIsId(String id) {
		return subjjectList().stream().filter(item->{
			if(item.getId().equals(id)){
				return true;
			}
			return false;
		}).collect(Collectors.toList());
	}

	@Override
	public void saveToSubject(SubjectSaveDTO subjectSaveDTO) throws MsgException, MsgException {
		Subject subject = subjectConversion.SubjectSaveVOToSubject(subjectSaveDTO);
		R<Img> img = imgClient.getImg(subject.getId());
		if(img.getData()==null){
			//TODO (cyq)添加异常信息
			throw new MsgException(1,"暂未添加");
		}
		String subjectName = subject.getName();
		//根据名字获取博客分类集合
		List<Subject> subjects = getSubjectIsName(subjectName);
		if(subjects!=null && subjects.size()!=0){
			throw new MsgException(CodeMsg.SUBJECT_EXISTS_CREATE_ERROR.getCode(),CodeMsg.SUBJECT_EXISTS_CREATE_ERROR.getMsg());
		}
		//添加数据库和redis
		subject.setCreateTime(LocalDateTime.now());
		subject.setUpdateTime(LocalDateTime.now());
		this.save(subject);
		Subject byId = this.getById(subject.getId());
		//刷新redis中的数据
		addSubject(byId);
	}

	@Override
	public void updToSubject(SubjectUpdDTO subjectUpdDTO) throws MsgException {
		Subject entity = subjectConversion.SubjectUpdVOToSubject(subjectUpdDTO);
		R<Img> img = imgClient.getImg(entity.getId());
		if(img.getData()==null || StringUtil.isBlank(img.getData().getId())){
			//TODO (cyq)添加异常信息
			throw new MsgException(1,"暂未添加");
		}
		this.updateById(entity);
		Subject byId = this.getById(entity.getId());
		updSubject(byId);
	}

	//点击增加
	private void clickToSubject(String id){
		List<Subject> blogCategories = subjjectList();
		List<Subject> collect = blogCategories.stream().map(item -> {
			if (item.getId().equals(id)) {
				item.setClickCount(item.getClickCount()+1);
			}
			return item;
		}).collect(Collectors.toList());
		redisUtil.set(CacheNames.BLOG_SUBJECTS, JSON.toJSON(collect));
	}

	//根据name从redis查找
	private List<Subject> getSubjectIsName(String subjectName) {
		List<Subject> subjects = subjjectList().stream().filter(item -> {
			if (subjectName.equals(item.getName())) {
				return true;
			}
			return false;
		}).collect(Collectors.toList());
		return subjects;
	}
	//传入的对象增加redis
	private void addSubject(Subject subject) {
		List<Subject> subjcets = subjjectList();
		subjcets.add(subject);
		redisUtil.set(CacheNames.BLOG_SUBJECTS, JSON.toJSON(subjcets));
	}
	//修改数据redis
	private void updSubject(Subject subject){
		List<Subject> subjects = subjjectList();
		List<Subject> collect = subjects.stream().map(item -> {
			if (item.getId().equals(subject.getId())) {
				return subject;
			}
			return item;
		}).collect(Collectors.toList());
		redisUtil.set(CacheNames.BLOG_SUBJECTS, JSON.toJSON(collect));
	}

}
